<?php

class Web_Admin_Pedidos_GenerarPedido extends Web_Admin_MainPage
{

    public function mainContent()
    {
        parent::add_js_link(BASE_WEB_ROOT . '/js/jquery.1.7.1.js');
        parent::add_js_link(BASE_WEB_ROOT . '/js/jquery.ui.1.8.16.js');
        parent::add_css_link(BASE_WEB_ROOT . '/css/jquery.ui.css');
        return $this->_getGenerarPedido();
    }

    private function _getGenerarPedido()
    {
        $carro = $_SESSION['eyoriacart'];
        
        global $db;

        if (isset($carro)) {
            foreach ($carro as $item) {

                $pro = $db->fetchRow($db->select()
                                        ->from('ma_productos', array('pro_nombre'))
                                        ->where('pro_id=?', $item['item_id']));

                $cart = new Ey_Carrito;
                
                $subtotal+= $cart->subtotal($cart->verifica_tipo($item['cantidad'], $item['item_price'], null, null, null, null), $item['cantidad'] * $item['item_price']);

                $importe = $cart->subtotal($cart->verifica_tipo($item['cantidad'], $item['item_price'], null, null, null, null), $item['cantidad'] * $item['item_price']);
                
                $eliminar = '<a href="' . WEB_ROOT . '/svc/elimina-elemento/' . $item['item_id'] . '"><img src="' . WEB_ROOT . '/img/delete.png" /></a>';
                
                $matriz[] = array('id' => $item['item_id'],
                    'nombre' => $pro->pro_nombre,
                    'precio' => $item['item_price'],
                    'cantidad' => $item['cantidad'],
                    'importe' => number_format($importe, 2, '.', ','),
                    'eliminar' => $eliminar);
                
            }
        }
        
        $_SESSION['matriz'] = $matriz;
        $_SESSION['subtotal'] = $subtotal;
        $total = $subtotal + $_SESSION['precioDelivery'];
        
        $select = $db->select()->from('ma_moneda', array('mon_valor'))->where('mon_key="dolar"');
        $moneda = $db->fetchRow($select);

        $obj = new Web_Db_Delivery();
        $cats = $obj->fetchAll($obj->select()
                                ->order('del_distrito')
                                ->where('del_estado=?', 1));
        $html = '';
        foreach ($cats as $cat) {            
            $html.= '<option id="' . $cat->del_id . '" value="' . round($cat->del_precio * $moneda->mon_valor, 2) . '"';
            $html.= $_SESSION['idDelivery'] == $cat->del_id ? ' selected="selected"' : '';
            $html.= '>' . $cat->del_distrito . '</option>';
        }
        
        $smarty = new Smarty_Engine();
        $smarty->assign('matriz', $matriz);
        $smarty->assign('html', $html);
        $smarty->assign('subtotal', $subtotal);
        $smarty->assign('total', $total);
        $smarty->assign('precioDelivery', $_SESSION['precioDelivery']);

        return $smarty->fetch(ADMIN_PEDIDOS_DIR . DS . 'tpl' . DS . 'generar-pedido.tpl');
    }

}